﻿using System;
using System.Collections.Generic;
using System.Threading;
using Jarvis.Server.Domain;
using Jarvis.Server.Persistence;
using Jarvis.Server.Providers;
using Jarvis.Server.Workers.Messages;
using ManagedWifi;
using NHibernate;
using Ninject.Extensions.Logging;
using Action = Jarvis.Server.Domain.Action;
using ILoggerFactory = Ninject.Extensions.Logging.ILoggerFactory;

namespace Jarvis.Server.Workers
{
    public class LocatorWorker :Worker
    {
        private Domain.Location _currentLocation = Location.NonRecognizedLocation;

        private readonly ILogger _logger;
        private readonly ILocationProvider _locationProvider;

        public LocatorWorker(ILogger logger, ILocationProvider locationProvider)
        {

            _logger = logger;
            _locationProvider = locationProvider;


            _locationProvider.StoreAsKnownLocation(new Location()
                                                       {
                                                           Actions = new List<Action>(){new ShowMessageAction(){Message = "Questo é un messaggio",Name = "Test Action"}},
                                                           Categories = new List<LocationCategory>(),
                                                           Name = "Locazione 1"
                                                       });

            Name = "Locator Worker";
        }

        #region Overrides of Worker

        public override void Loop()
        {
            
            _logger.Trace("Current Location is: {0}", _currentLocation.Name);

            var newCurrentLocation = _locationProvider.ComputedLocation ?? Location.NonRecognizedLocation;

            if(!(Equals(newCurrentLocation, _currentLocation)))
            {
                _logger.Trace("Location Changed from {0} to {1}",_currentLocation.Name,newCurrentLocation.Name);
                SendMessage(new CurrentLocationChangedMessage(){Location = newCurrentLocation});
            }

            _currentLocation = newCurrentLocation;
        }

        public override void OnMessageReceived(Message message)
        {
            if(message is CurrentLocationChangedMessage)
            {
                _logger.Trace("Received message");
            }
        }

        #endregion
    }
}
